package com.xc.quickstart.common.interceptor;

import com.alibaba.fastjson.JSON;
import com.xc.quickstart.common.annotation.Token;
import com.xc.quickstart.common.context.ApiContext;
import com.xc.quickstart.common.model.ApiContextModel;
import com.xc.quickstart.common.model.ApiResponse;
import com.xc.quickstart.common.model.JwtParseModel;
import com.xc.quickstart.common.util.JwtUtil;
import com.xc.quickstart.service.LoginBizService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;

@Slf4j
@Component
public class ApiTokenInterceptor extends HandlerInterceptorAdapter {

    private static final String XCTOKEN = "xctoken";

    private static final String MERCHANT = "xcmchid";

    private static final Set<String> METHOD_NAME_WHITE_SET = new HashSet<>();

    static {
        METHOD_NAME_WHITE_SET.add("uploadImg");
        METHOD_NAME_WHITE_SET.add("uploadWatermarkImg");
    }

    @Autowired
    @Lazy
    private LoginBizService loginBizService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        if (!judge(handler)) {
            return true;
        }

        String token = request.getHeader(XCTOKEN);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");

        if (StringUtils.isEmpty(token)) {
            log.warn("未获取到:token");
            response.getWriter().print(JSON.toJSONString(ApiResponse.noLogin()));
            response.getWriter().close();
            return false;
        }

        //解析
        JwtParseModel jwtParseModel = JwtUtil.parse(token);
        if (!jwtParseModel.isSuccess()) {
            log.warn("token解析失败,{}", JSON.toJSONString(jwtParseModel));
            response.getWriter().print(JSON.toJSONString(ApiResponse.noLogin(jwtParseModel.getMsg())));
            response.getWriter().close();
            return false;
        }

        //检验
        if (!loginBizService.checkToken(jwtParseModel.getClaims().get("userId").toString()
                , jwtParseModel.getClaims().get("jobNumber").toString()
                , token)) {
            log.warn("token校验失败,{}", JSON.toJSONString(jwtParseModel));
            response.getWriter().print(JSON.toJSONString(ApiResponse.noLogin()));
            response.getWriter().close();
            return false;
        }

        String xcmchid = request.getHeader(MERCHANT);
        Method method = ((HandlerMethod) handler).getMethod();
        if (!METHOD_NAME_WHITE_SET.contains(method.getName())
                && (StringUtils.isEmpty(xcmchid) || Integer.parseInt(xcmchid) <= 0)) {
            log.warn("商户未传,{}", xcmchid);
            response.getWriter().print(JSON.toJSONString(ApiResponse.noLogin()));
            response.getWriter().close();
            return false;
        }

        ApiContextModel apiContextModel = ApiContext.getApiContextModel();
        apiContextModel.setXcmchid(StringUtils.isNumeric(xcmchid) ? Integer.parseInt(xcmchid) : 0);
        apiContextModel.setUserId(Integer.valueOf(jwtParseModel.getClaims().get("userId").toString()));
        apiContextModel.setJobNumber(jwtParseModel.getClaims().get("jobNumber").toString());
        apiContextModel.setUserName(jwtParseModel.getClaims().get("userName").toString());
        return true;
    }

    private boolean judge(Object handler) {
        if (!(handler instanceof HandlerMethod)) {
            return false;
        }

        Method method = ((HandlerMethod) handler).getMethod();
        Class<?> declaringClass = method.getDeclaringClass();

        if (Objects.isNull(declaringClass.getAnnotation(RequestMapping.class))) {
            return false;
        }

        Token annotation = method.getAnnotation(Token.class);
        if (Objects.isNull(annotation)) {
            annotation = declaringClass.getAnnotation(Token.class);
        }

        if (Objects.nonNull(annotation) && !annotation.ignore()) {
            return true;
        }

        return false;
    }


}
